#include "musiclist.h"

#include <QMimeDatabase>
#include <QMimeType>
#include <QDebug>
#include <QSqlQuery>
#include <QSqlError>

MusicList::MusicList()
{

}

void MusicList::addMusicByUrl(const QList<QUrl> &urls)
{
    QMimeDatabase mimeDB;

    for(auto& e : urls)
    {
        //验证url是否在musicPaths中
        QString path = e.toLocalFile();

        if(musicPaths.contains(path))
            continue;

        //如果没有 , 添加到 paths 和 musicList中
        musicPaths.insert(path);

        //再次验证是否是有效文件
        QMimeType mimeType = mimeDB.mimeTypeForFile(e.toLocalFile());
        QString name = mimeType.name();

        if(name == "audio/mpeg" || name == "audio/flac" || name == "audio/wav")
        {
            Music music(e);
            musicList.push_back(music);
        }
    }
}

MusicList::iterator MusicList::begin()
{
    return musicList.begin();
}

MusicList::iterator MusicList::end()
{
    return musicList.end();
}

void MusicList::writeToDB()
{
    for(auto music : musicList)
    {
        music.insertMusicToDB();
    }
}

void MusicList::readFromDB()
{
    QString sql("SELECT musicid, musicName, musicSigner, albumName,\
                    duration, musicUrl, isLike, isHistory \
                 FROM musicInfo");
    QSqlQuery query;
    if(!query.exec(sql))
    {
        qDebug()<<"数据库查询失败" << query.lastError().text();
        return;
    }

    qDebug() << "数据库查询成功";
    while(query.next())
    {

        Music music;

        music.setMusicID(query.value(0).toString());

        music.setMusicName(query.value(1).toString());

        music.setSignerName(query.value(2).toString());

        music.setAlbumName(query.value(3).toString());

        music.setDuration(query.value(4).toLongLong());

        music.setMusicUrl("file:///" + query.value(5).toString());

        music.setIsLike(query.value(6).toBool());

        music.setIsLike(query.value(7).toBool());

        musicList.push_back(music);

        musicPaths.insert(music.getMusicUrl().toLocalFile());
    }
}

MusicList::iterator MusicList::findMusicById(const QString &musicId)
{
    for(iterator it = begin() ; it != end() ; ++it)
    {
        if(it->getMusicID() == musicId)
        {
            return it;
        }
    }
    return end();
}
